package com.leaf.spring.y201911.day27;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 测试HashMap线程不安全
 * 
 * @Title:
 * @Description: 以下代码多运行几次会出现死循环或数组越界的情况，其实是由于HashMap线程不安全导致的
 * @Author:gaowenjin
 * @Since:2019年11月27日
 * @Version:1.1.0
 */
public class HashMapTest {

	public static void main(String[] args) {

		HashMapThread m1 = new HashMapThread();
		HashMapThread m2 = new HashMapThread();
		HashMapThread m3 = new HashMapThread();
		HashMapThread m4 = new HashMapThread();
		HashMapThread m5 = new HashMapThread();
		
		m1.start();
		m2.start();
		m3.start();
		m4.start();
		m5.start();

	}
}

class HashMapThread extends Thread {

	AtomicInteger ato = new AtomicInteger();
	Map<Integer, Integer> atoMap = new HashMap<>();

	@Override
	public void run() {

		while (ato.get() < 10000000) {
			atoMap.put(ato.get(), ato.get());
			ato.incrementAndGet();
		}

	}

}
